package com.rongxun.hbwallet.mvp.presenter;

import android.support.annotation.NonNull;

import com.rongxun.base.BasePresenter;
import com.rongxun.base.ResponseSubscriber;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.ConfigKey;
import com.rongxun.hbwallet.model.bean.Config;
import com.rongxun.hbwallet.model.bean.Order;
import com.rongxun.hbwallet.model.bean.Wallet;
import com.rongxun.hbwallet.mvp.contract.ITransfer;
import com.rongxun.hbwallet.mvp.model.ApiModel;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.RxUtil;
import com.rongxun.utils.ToastUtils;
import com.rongxun.utils.wallet.TransactionUtils;
import com.rongxun.utils.wallet.WalletSubscriber;

import java.math.BigDecimal;
import java.math.BigInteger;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableOnSubscribe;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/8/20 13:54
 * 描述	      转账充值
 */

public class TransferPresenter extends BasePresenter<ITransfer.IView, ApiModel> implements ITransfer.IPresenter {
    public TransferPresenter(@NonNull ITransfer.IView pUi) {
        super(pUi);
    }

    public TransferPresenter(@NonNull ITransfer.IView pUi, @NonNull ApiModel pModel) {
        super(pUi, pModel);
    }

    @Override
    public void getEthBalance(String fromAddress) {
        addSubscribe(Flowable.create((FlowableOnSubscribe<BigDecimal>) e -> {
            BigDecimal ethBalance = TransactionUtils.getEthBalance(fromAddress);
            e.onNext(ethBalance);
            e.onComplete();
        }, BackpressureStrategy.BUFFER)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new WalletSubscriber<BigDecimal>(getView()) {
                    @Override
                    public void onSuccess(BigDecimal bigInteger) {
                        getView().showEthBalance(bigInteger);
                    }

                    @Override
                    public void disposeEorCode(String message, String code) {

                    }
                }));

    }

    @Override
    public void getTokenBalance(String fromAddress) {
        addSubscribe(Flowable.create((FlowableOnSubscribe<BigInteger>) e -> {
            BigInteger ethBalance = TransactionUtils.getTokenBalance(fromAddress);
            e.onNext(ethBalance);
            e.onComplete();
        }, BackpressureStrategy.BUFFER)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new WalletSubscriber<BigInteger>(getView()) {
                    @Override
                    public void onSuccess(BigInteger bigInteger) {
                        getView().showTokenBalance(bigInteger);
                    }

                    @Override
                    public void disposeEorCode(String message, String code) {

                    }
                }));
    }

    @Override
    public void getGasPrice() {

        addSubscribe(Flowable.create((FlowableOnSubscribe<BigInteger>) e -> {
            BigInteger ethBalance = TransactionUtils.getTransactionGasPrice();
            e.onNext(ethBalance);
            e.onComplete();
        }, BackpressureStrategy.BUFFER)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new WalletSubscriber<BigInteger>(getView()) {
                    @Override
                    public void onSuccess(BigInteger bigInteger) {
                        getView().showGasPrice(bigInteger);
                    }

                    @Override
                    public void disposeEorCode(String message, String code) {

                    }
                }));

    }

    @Override
    public void getGasLimit(String fromAddress) {

    }

    @Override
    public void transfer(String password, String fromAddress, String toAddress, BigInteger amount, BigInteger gasLimit, BigInteger gasPrice) {
        addSubscribe(Flowable.create((FlowableOnSubscribe<String>) e -> {

            String txHash = TransactionUtils.sendTokenTransaction(fromAddress, password, toAddress, amount, gasPrice, gasLimit);
            e.onNext(txHash);
            e.onComplete();
        }, BackpressureStrategy.BUFFER)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new WalletSubscriber<String>(getView()) {
                    @Override
                    public void onSuccess(String txHash) {
                        getView().showTransferResult(txHash);
                    }

                    @Override
                    public void disposeEorCode(String message, String code) {

                    }
                }));
    }

    @Override
    public void recharge(String password, String fromAddress, String toAddress, BigDecimal amount, BigInteger gasLimit, BigInteger gasPrice) {
        addSubscribe(Flowable.create((FlowableOnSubscribe<String>) e -> {
            String txHash = TransactionUtils.sendTransaction(fromAddress, password, toAddress, gasPrice, gasLimit, amount);
            e.onNext(txHash);
            e.onComplete();
        }, BackpressureStrategy.BUFFER)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new WalletSubscriber<String>(getView()) {
                    @Override
                    public void onSuccess(String txHash) {
                        getView().showRechargeResult(txHash);
                    }

                    @Override
                    public void disposeEorCode(String message, String code) {

                    }
                }));
    }

    @Override
    public void checkTransferInfo(String address, String transfer, BigDecimal ethBalance, String gas, BigInteger tokenBalance) {
        if (address.isEmpty() || !address.startsWith("0x")) {
            ToastUtils.showToast(R.string.no_address);
            return;
        }

        if (transfer == null || transfer.isEmpty() || transfer.equals("0")) {
            ToastUtils.showToast(R.string.no_money);
            return;
        }

        BigDecimal transferNum = new BigDecimal(transfer);
        BigDecimal gasNum = new BigDecimal(gas);
        BigDecimal tokenBalanceNum = new BigDecimal(tokenBalance);


        //eth低于gas或者代币少于输入金额
        if (ethBalance.compareTo(gasNum) == -1) {
            ToastUtils.showToast(R.string.eth_not_sufficient_funds);
            return;
        }

        if (tokenBalanceNum.compareTo(transferNum) == -1) {
            ToastUtils.showToast(R.string.not_sufficient_funds);
            return;
        }

        getView().showTransferInfo();
    }

    @Override
    public void getRechargeMin() {

        addSubscribe(getModel().getTokenConfig(ConfigKey.RECHARGE_MIN).subscribeWith(new ResponseSubscriber<Config>(getView()) {
            @Override
            public void onSuccess(Config config) {
                FlyLog.i(config.getData());
                getView().showRechargeMin(config.getData());
            }

            @Override
            public void disposeEorCode(String message, String code) {
            }
        }));

    }

    @Override
    public void checkRechargeInfo(String address, String rechargeMoney, double minRecharge, BigDecimal realEth, String gas, BigDecimal ethBalance) {
        if (address.isEmpty() || !address.startsWith("0x")) {
            ToastUtils.showToast(R.string.no_address);
            return;
        }

        if (rechargeMoney == null || rechargeMoney.isEmpty() || rechargeMoney.equals("0")) {
            ToastUtils.showToast(R.string.no_money);
            return;
        }


        BigDecimal rechargeNum = new BigDecimal(rechargeMoney);//代币数量
        BigDecimal minRechargeNum = new BigDecimal(minRecharge);//最小代币数

        BigDecimal gasNum = new BigDecimal(gas);//gas


        //代币低于最低
        if (rechargeNum.compareTo(minRechargeNum) == -1) {
            String format = String.format(getView().getContext().getString(R.string.below_minimum), minRechargeNum.toPlainString());
            ToastUtils.showToast(format);
            return;
        }

        if (ethBalance.compareTo(gasNum.add(realEth)) == -1) {
            ToastUtils.showToast(R.string.eth_not_sufficient_funds);
            return;
        }


        getView().showTransferInfo();
    }


    @Override
    public void saveRecharge(String amount, String fromaddress, Double gas, String toaddress, String txhash, String uid) {
        addSubscribe(getModel()
                .saveRecharge(amount, fromaddress, gas, toaddress, txhash, uid)
                .subscribeWith(new ResponseSubscriber<Wallet>(getView()) {
                    @Override
                    public void onSuccess(Wallet s) {
                        getView().showRechargeSuccess(txhash);
                    }

                    @Override
                    public void disposeEorCode(String message, String code) {

                    }
                }));
    }

    @Override
    public void buy(String amount, String fromaddress, Double gas, String toaddress, String trxhash, String uid) {
        addSubscribe(getModel()
                .buy(amount, fromaddress, gas, toaddress, trxhash, uid)
                .subscribeWith(new ResponseSubscriber<Order>(getView()) {
                    @Override
                    public void onSuccess(Order s) {
                        getView().showRechargeSuccess(trxhash);
                    }

                    @Override
                    public void disposeEorCode(String message, String code) {

                    }
                }));
    }

    @Override
    public void getEthToToken() {
        addSubscribe(getModel().getTokenConfig(ConfigKey.EXCHANGE_RATE).subscribeWith(new ResponseSubscriber<Config>(getView()) {
            @Override
            public void onSuccess(Config config) {
                getView().showEthToToken(config.getData());
            }

            @Override
            public void disposeEorCode(String message, String code) {
            }
        }));

    }

    @Override
    public void getAdminAddress() {
        addSubscribe(getModel().getTokenConfig(ConfigKey.ADMIN_ADRESS).subscribeWith(new ResponseSubscriber<Config>(getView()) {
            @Override
            public void onSuccess(Config config) {
                getView().showAdminAdress(config.getData());
            }

            @Override
            public void disposeEorCode(String message, String code) {
            }
        }));
    }
}
